package com.cwits.wifi.prapi;


import android.os.Environment;

import com.cwits.wifi.base.BaseAPI;
import com.cwits.wifi.base.BaseActivity;
import com.cwits.wifi.util.Dbug;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * Created by ZhangHua on 2016/3/28.
 */
public class ProjectAPI extends BaseAPI{

    public interface OnOBDDevicesIP{
        void getOBDDevicesIP(int errorcode,String json);
    }


    public static void getOBDDevicesIP(String PN,final OnOBDDevicesIP listener){
        if (client == null) {
            client = new AsyncHttpClient();

        }
        client.get("http://192.168.43.1:5000/GetConnectionDevInfo?pn=" + PN, null, new AsyncHttpResponseHandler() {

            public void onStart() {

            }

            public void onSuccess(String response) {

                listener.getOBDDevicesIP(200,response);
            }

            public void onFailure(Throwable e, String response) {
                e.printStackTrace();
                listener.getOBDDevicesIP(201,response);
            }

            public void onFinish() {

            }
        });
        //request("http://192.168.43.1:5000/GetConnectionDevInfo?pn=" + PN, params, "GET", listener, requestCode);
    }

    /**
     * 获取oauth
     * @param listener
     * @param user_id
     * @param requestCode
     */
    public void getOauth(final BaseActivity listener,String user_id,int requestCode){
        String client_id = "352ADFE08F6B8C972AB5B1E959732E6C";
        String client_secret = "123456";
        String grant_type = "client_credentials";
        RequestParams params = new RequestParams();
        params.put("client_id",client_id);
        params.put("client_secret", client_secret);
        params.put("grant_type", grant_type);
        params.put("user_id", user_id);
        //request("http://develop.9555168.com:88/appserver/oauth/token?", params, "POST", listener, requestCode);
        request("http://crapp.kcnzq.net:8800/appserver/oauth/token?", params, "POST", listener, requestCode);
    }
    /**
     * 获取更新基础数据
     * @param listener
     * @param token
     * @param requestCode
     */
    public void getUpdateMobileRecord(final BaseActivity listener, String token,String user_id,String app_id,String soft_id,String ter_id,String cid_id,int requestCode){
        String client_id = "352ADFE08F6B8C972AB5B1E959732E6C";
        RequestParams params = new RequestParams();
        params.put("client_id",client_id);
        params.put("user_id", user_id);
        params.put("token", token);
        params.put("app_id", app_id);
        params.put("soft_id", soft_id);
        params.put("ter_id", ter_id);
        params.put("cid", cid_id);
        //request("http://develop.9555168.com:88/appserver/tachograph/user/info?", params, "POST", listener, requestCode);
        request("http://crapp.kcnzq.net:8800/appserver/tachograph/user/info?", params, "POST", listener, requestCode);
    }


    /**
     * 获取服务端版本信息
     * @param listener
     * @param token
     * @param requestCode
     */
    public void getSoftVersionInfo(final BaseActivity listener, String token,String user_id,String ter_id,String soft_id,int requestCode){
        String client_id = "352ADFE08F6B8C972AB5B1E959732E6C";
        RequestParams params = new RequestParams();
        params.put("client_id",client_id);
        params.put("user_id", user_id);
        params.put("token", token);
        params.put("ter_id", ter_id);
        params.put("soft_id", soft_id);
        //request("http://develop.9555168.com:88/appserver/tachograph/version/info?", params, "POST", listener, requestCode);
        request("http://crapp.kcnzq.net:8800/appserver/tachograph/device/version?", params, "POST", listener, requestCode);
    }


    /**
     * 获取服务端版本信息
     * @param listener
     * @param requestCode
     */
    public void getPengciInfo(final BaseActivity listener, int SearchType,String SearchValue,int requestCode){
        RequestParams params = new RequestParams();
        //params.put("Content-Type","application/x-www-form-urlencoded");
        //params.put("Accept-Language","zh-CN,zh;q=0.8");
        params.put("SearchType",String.valueOf(SearchType));
        params.put("SearchValue", SearchValue);
        request("http://cross.kcnzq.net:8099/CarRecorder/InsuranceManage/InsuranceSearchInfo", params, "POST", listener, requestCode,2);
    }


    /**
     * 获取服务端版本信息
     * @param listener
     * @param token
     * @param requestCode
     */
    public void getAPPVersionInfo(final BaseActivity listener, String token,String user_id,String app_id,int requestCode){
        String client_id = "352ADFE08F6B8C972AB5B1E959732E6C";
        RequestParams params = new RequestParams();
        params.put("client_id",client_id);
        params.put("user_id", user_id);
        params.put("token", token);
        params.put("app_id", app_id);
        //request("http://develop.9555168.com:88/appserver/tachograph/version/info?", params, "POST", listener, requestCode);
        request("http://crapp.kcnzq.net:8800/appserver/tachograph/app/version?", params, "POST", listener, requestCode);
    }


    /**
     * 记录每天登录信息
     * @param listener
     * @param token
     * @param requestCode
     */
    public void recordDayRun(final BaseActivity listener, String token,String user_id,String data,int requestCode){
        String client_id = "352ADFE08F6B8C972AB5B1E959732E6C";
        RequestParams params = new RequestParams();
        params.put("client_id",client_id);
        params.put("user_id", user_id);
        params.put("token", token);
        params.put("data", data);
        //request("http://develop.9555168.com:88/appserver/tachograph/dayrun/data?", params, "POST", listener, requestCode);
        request("http://crapp.kcnzq.net:8800/appserver/tachograph/dayrun/data?", params, "POST", listener, requestCode);
    }

    /**
     * 记录个推信息
     * @param listener
     * @param token
     * @param requestCode
     */
    public void recordClientInfo(final BaseActivity listener, String token,String user_id,String cid,int requestCode){
        String client_id = "352ADFE08F6B8C972AB5B1E959732E6C";
        RequestParams params = new RequestParams();
        params.put("client_id",client_id);
        params.put("user_id", user_id);
        params.put("token", token);
        params.put("cid", cid);
        //request("http://develop.9555168.com:88/appserver/tachograph/client/info?", params, "POST", listener, requestCode);
        request("http://crapp.kcnzq.net:8800/appserver/tachograph/client/info?", params, "POST", listener, requestCode);
    }

    public void downloadSoft(final BaseActivity listener,final String url_str,final String soft_name,final String soft_size,final String soft_md5)
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url;
                HttpURLConnection connVerDesc = null;
                String verDescFileName = url_str;
                File verDescFilePath = new File(Environment.getExternalStorageDirectory()
                        .getAbsolutePath() + "/lipeibao/168cardev/"
                        + "/com.cwits.wifi/"
                        + "VersionFiles/");
                boolean result = false;
                String namepath = "";
                if(!verDescFilePath.exists())
                    verDescFilePath.mkdirs();
                File verDescFile = new File(Environment.getExternalStorageDirectory()
                        .getAbsolutePath() + "/lipeibao/168cardev/"
                        + "/com.cwits.wifi/"
                        + "VersionFiles/" + soft_name);

                try {
                    if (!verDescFile.exists()) {
                        FileOutputStream outFile = new FileOutputStream(verDescFile);
                        url = new URL(url_str);
                        connVerDesc = (HttpURLConnection) url.openConnection();
                       // connVerDesc.setRequestMethod("POST");
                        connVerDesc.setRequestProperty("Charset", "UTF-8");
                        //connVerDesc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
                        connVerDesc.setRequestProperty("Connection", "Keep-Alive");
                        connVerDesc.connect();
                        if (connVerDesc != null && !connVerDesc.equals("")) {
                            int i = connVerDesc.getContentLength();
                            Dbug.i("ProjectAPI","-------InputStream----size:" + i);
                            //InputStream inVerDesc = connVerDesc.getInputStream();
                            BufferedInputStream inVerDesc = new BufferedInputStream(connVerDesc.getInputStream());

                            int len = 0;
                            byte[] buffer = new byte[1024];
                            while ( (len = inVerDesc.read(buffer)) != -1 ) {
                                outFile.write(buffer,0,len);
                                //outFile.flush();// 刷新缓冲区
                            }
                            Dbug.i("ProjectAPI","-------FileOutputStream----size:" + verDescFile.length());
                            inVerDesc.close();
                            outFile.close();

                            result = true;
                            namepath = verDescFile.getAbsolutePath();
                        }
                    }else
                    {
                        result = true;
                        namepath = verDescFile.getAbsolutePath();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    verDescFile.delete();
                } finally {
                    if (null != connVerDesc)
                        connVerDesc.disconnect();
                }

               if(result){
                   listener.onDownloadSoft(true,namepath,soft_name);
               }else{
                   listener.onDownloadSoft(false,"",soft_name);
               }
            }
        }).start();
    }
}
